package com.rw.base.http;

import android.content.Context;

import java.lang.ref.WeakReference;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.Scheduler;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * @author: ZengZhenHua
 * @date: 2018/12/18
 * @email: cengzhenghua@163.com
 */
public class HttpManager {
    private volatile static HttpManager  mInstance= null;
    private WeakReference<Context> mContext;
    private Observable mObservable;
    private BaseObserver mObserver;

    private HttpManager(){

    }

    public static HttpManager getInstance() {
        if(mInstance == null ){
            synchronized (HttpManager.class){
                if (mInstance == null){
                    mInstance = new HttpManager();
                }
            }
        }
        return mInstance;
    }

    public HttpManager with(Context context){
        mContext = new WeakReference<>(context);
        return mInstance;
    }

    public HttpManager setObservable(Observable observable){
        this.mObservable = observable.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
        return mInstance;
    }

    public <T> void setDataListener(HttpDataCallback<T> dataListener){
        mObserver = new BaseObserver<T>(dataListener);
        mObservable.subscribe(mObserver);
    }

    //取消请求
    public void cancelRequest() {
        if (mObserver!=null){
            mObserver.cancelRequest();
        }
    }
}
